package com.spzx.common.security.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.utils.ServletUtils;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.security.auth.AuthUtil;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.system.api.model.LoginUser;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author spzx
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor
{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        //handler一般就是controller中方法。
        if (!(handler instanceof HandlerMethod))
        {
            return true;
        }

        //请求头信息被gateway网关中全局过滤器存放的： AuthFilter
        SecurityContextHolder.setUserId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID));
        SecurityContextHolder.setUserName(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USERNAME));
        SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));

        //Authorization = Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6ImRhNTY2ZTlkLTVkNmEtNDU1Mi1hY2QzLWYyODZmNDAwNDU5ZSIsInVzZXJuYW1lIjoiYWRtaW4ifQ.VEvt3RZkF91U_i8efRP56BZer11YaXOOYZdlqbba98vt2uWjaTQWIJAndF_5v4I9726MQPYDGvmitDMdQNaYrw
        //将 'Bearer '替换为''返回剩余令牌内容(JWT令牌)
        //JWT令牌3个组成部分：头，载体，签名
        String token = SecurityUtils.getToken();
        if (StringUtils.isNotEmpty(token))
        {
            //解析JWT令牌，获取user_key,拼上前缀，从redis中查找用户登录信息
            //redisKey:    login_tokens:da566e9d-5d6a-4552-acd3-f286f400459e   绑定登录用户信息
            LoginUser loginUser = AuthUtil.getLoginUser(token);
            if (StringUtils.isNotNull(loginUser))
            {
                AuthUtil.verifyLoginUserExpire(loginUser); //登录后令牌有效时间为12小时   当时间小于2小时刷新时间为12小时
                SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser); //将用户信息绑定到线程上。
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception
    {
        SecurityContextHolder.remove();
    }
}
